import { useState, useEffect } from 'react'
import { isWechatBrowser, getUrlParam, redirectToWechatAuth, getUserInfoByCode, initWechatJSSDK, getWechatJSSDKConfig } from '@/utils/wechat'
import type { WechatUserInfo } from '@/types/wechat'

export const useWechatAuth = () => {
  const [userInfo, setUserInfo] = useState<WechatUserInfo | null>(null)
  const [loading, setLoading] = useState<boolean>(false)
  const [error, setError] = useState<string | null>(null)
  const [isWechat, setIsWechat] = useState<boolean>(false)

  useEffect(() => {
    setIsWechat(isWechatBrowser())

    const code = getUrlParam('code')
    const state = getUrlParam('state')

    if (code && state) {
      handleAuthCallback(code)
    }

    initializeWechatSDK()
  }, [])

  const handleAuthCallback = async (code: string) => {
    setLoading(true)
    setError(null)

    try {
      const userData = await getUserInfoByCode(code)
      setUserInfo(userData)

      const url = new URL(window.location.href)
      url.searchParams.delete('code')
      url.searchParams.delete('state')
      window.history.replaceState({}, document.title, url.toString())
    } catch (err: any) {
      setError('获取用户信息失败: ' + (err?.message || String(err)))
      console.error('授权失败:', err)
    } finally {
      setLoading(false)
    }
  }

  const initializeWechatSDK = async () => {
    if (!isWechatBrowser()) return
    try {
      const config = await getWechatJSSDKConfig()
      await initWechatJSSDK(config)
    } catch (err) {
      console.warn('微信JS-SDK初始化失败:', err)
    }
  }

  const startAuth = () => {
    if (!isWechat) {
      setError('请在微信中打开此页面')
      return
    }
    setError(null)
    try {
      redirectToWechatAuth()
    } catch (err: any) {
      setError(err.message || '授权跳转失败')
    }
  }

  const logout = () => {
    setUserInfo(null)
    setError(null)
    localStorage.removeItem('wechat_user_info')
  }

  const refreshUserInfo = async () => {
    if (!userInfo) return
    setLoading(true)
    setError(null)
    try {
      console.log('用户信息刷新功能需要后端支持')
    } catch (err: any) {
      setError('刷新用户信息失败: ' + (err?.message || String(err)))
    } finally {
      setLoading(false)
    }
  }

  return {
    userInfo,
    loading,
    error,
    isWechat,
    startAuth,
    logout,
    refreshUserInfo,
    isAuthenticated: !!userInfo,
  }
}
